package com.ali.config;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.util.HashMap;

/**
 * 自定义用户登录成功处理器
 */
@Slf4j
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        //获取用户信息
        Object principal = authentication.getPrincipal();
        User principalUser = (User) principal;

        String token = JWTUtil.getToken(principalUser.getUsername(), 60);

        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "登陆成功");
        result.put("token", token);

        String json = JSON.toJSONString(result);

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
    }
}
